﻿using HR.Config;
using HR.IService;
using HR.Models;

namespace HR.Service
{
    public class Config_MajorService : IConfig_MajorService
    {
        private readonly HRDBContext db;

        public Config_MajorService(HRDBContext db)
        {
            this.db = db;
        }

        public Task<int> CMajorAdd(config_major cm)
        {
            return Task.Run(() =>
            {
                config_major? cfm = db.config_majors.OrderByDescending(cm => cm.major_id).FirstOrDefault();
                //说明该职位类型下有职工岗位
                if (cfm != null)
                {
                    int res;
                    //去除左侧'0'后进行递增重新组装字符串
                    int.TryParse(cfm.major_id.TrimStart('0'),out res);
                    cm.major_id = '0' + (res + 1).ToString();
                }
                cm.test_amount = 0;
                db.config_majors.Add(cm);
                return db.SaveChanges();
            });
        }

        public Task<int> CMajorDelete(short mak_id)
        {
            return Task.Run(() =>
            {
                config_major? cm = db.config_majors.Find(mak_id);
                db.config_majors.Remove(cm);
                return db.SaveChanges();
            });
        }

        public Task<Paging<config_major>> CMajorFill(int pgsize, int pgcurrent)
        {
            return Task.Run(() =>
            {
                List<config_major> list = db.config_majors.ToList();
                List<config_major> cms = list.Skip((pgcurrent - 1) * pgsize).Take(pgsize).ToList();
                Paging<config_major> pg = new Paging<config_major>()
                {
                    rows = list.Count,
                    tabs = cms
                };
                return pg;
            });
        }

        public Task<int> CMajorUpdate(config_major cm)
        {
            return Task.Run(() =>
            {
                config_major? cmr = db.config_majors.Find(cm.mak_id);
                cmr.major_id = cm.major_id;
                cmr.major_name = cm.major_name;
                cmr.major_kind_id = cm.major_kind_id;
                cmr.major_kind_name = cm.major_kind_name;
                return db.SaveChanges();
            });
        }

        public Task<List<config_major_kind>> CMKindsFill()
        {
            return Task.Run(() =>
            {
                return db.config_major_kinds.ToList();
            });
        }
    }
}
